import { Button, Form, Input, Select, Modal, InputNumber, DatePicker, message } from 'antd';
import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { COUPON_TYPE, PLATFORM_TYPE, COUPON_USE_TYPE, YYYY_MM_DD } from '@/common/constants';
import moment from 'moment';
import { updateRule, addRule } from '../service';


const { RangePicker } = DatePicker;

interface IRef {
  edit?: () => any;
  callback?: () => any;
}




const AddModal: React.ForwardRefRenderFunction<IRef, any> = (props, ref) => {

  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [btnLoading, setBtnLoading] = useState<boolean>(false);
  const [editRow, setEditRow] = useState<any>(null);

  const { callback } = props;

  /**
 * 添加节点
 * @param fields
 */
  const updateItem = async (fields: any, id: any) => {
    setBtnLoading(true);
    const isAdd = !id;
    const txt = isAdd ? '添加' : '编辑';
    const params = { ...fields };
    if (!isAdd) {
      Object.assign(params, { id });
    }
    try {
      if (isAdd) {
        await addRule(params);
      } else {
        delete params.id;
        await updateRule(id, params);
      }
    } catch (error) {
      message.error(`${txt}失败请重试！`);
      return false;
    } finally{
      setBtnLoading(false)
    }
  };


  const handleCancel = () => {
    setModalVisible(false);
    form.resetFields(['name', 'config']);
  };

  const getInitialValues = async (row: any) => {
    if (row?.id) form.setFieldsValue(row);
  };

  // 关闭弹窗 去掉loading
  useEffect(() => {
    if (!modalVisible) setBtnLoading(false);
  }, [modalVisible]);

  useImperativeHandle(ref, () => ({
    edit: (row?: any) => {
      setEditRow(row);
      if (row) getInitialValues(row);
      setModalVisible(true);
    }
  }));

  const handleOk = () => {
    console.log(111);
    form.validateFields().then((data) => {
      data.coupon_start_time = data.date[0].valueOf();
      data.coupon_end_time = data.date[1].valueOf();
      delete data.date;
      updateItem(data, editRow?.id).then(() => {
        setModalVisible(false);
        callback?.();
      });
    })
  };

  return (
    <>
      <Button
        onClick={() => {
          setEditRow(null);
          setModalVisible(true);
        }}
        type='primary'>
        新增
      </Button>
      <Modal
        title={
          editRow
            ? '编辑优惠券'
            : '新增优惠券'
        }
        onCancel={handleCancel}
        onOk={handleOk}
        visible={modalVisible}
        width={640}
        maskClosable={false}
        okButtonProps={{
          loading: btnLoading
        }}
        >
        <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 16 }} >
          <Form.Item label="优惠卷类型" name="type" initialValue={0} required rules={[{ required: true, message: '优惠卷类型不能为空' }]}>
            <Select options={COUPON_TYPE} />
          </Form.Item>
          <Form.Item label="优惠券名称" name="name" required rules={[{ required: true, message: '优惠券名称不能为空' }]}>
            <Input />
          </Form.Item>
          <Form.Item label="适用平台" name="platform" initialValue={0} required rules={[{ required: true, message: '适用平台不能为空' }]}>
            <Select options={PLATFORM_TYPE} />
          </Form.Item>
          <Form.Item label="总发行量" name="count" required rules={[{ required: true, message: '总发行量不能为空' }]}>
            <InputNumber min={1} max={1000000} precision={0} />
          </Form.Item>
          <Form.Item label="面额" name="amount" required rules={[{ required: true, message: '面额不能为空' }]}>
            <InputNumber addonAfter="元" min={1} max={1000000} precision={2} />
          </Form.Item>
          <Form.Item label="每人限领" name="per_limit" initialValue={1} required rules={[{ required: true, message: '面额不能为空' }]}>
            <InputNumber addonAfter="张" min={1} max={100} precision={0} />
          </Form.Item>
          <Form.Item label="使用门槛" name="min_point" required rules={[{ required: true, message: '面额不能为空' }]}>
            <InputNumber addonBefore="满" addonAfter="元可用" min={0} max={100} precision={0} />
          </Form.Item>
          <Form.Item
            name={['date']}
            label="有效期"
            required rules={[{ required: true, message: '有效期不能为空' }]}
            initialValue={[moment(), moment()]}
          >
            <RangePicker
              format={YYYY_MM_DD}
            />
          </Form.Item>
          <Form.Item label="可使用商品" name="use_type" initialValue={0} required rules={[{ required: true, message: '可使用商品不能为空' }]}>
            <Select options={COUPON_USE_TYPE} />
          </Form.Item>
          <Form.Item label="备注" name="note" initialValue={''}>
            <Input.TextArea />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default forwardRef(AddModal);
